<template>
    <div class="content-wrap">
        <div class="content-top-box" v-if="addBtn">
            <!-- 搜索区域 -->
            <ul class="search-container">
                <li>
                    <el-button class="search-btn" type="primary" icon="el-icon-plus" @click="addFn">新增</el-button>
                </li>
            </ul>
        </div>

        <div class="content-bottom-box">
            <!-- 表格 -->
            <div class="content-form-box">
                <el-table
                    v-loading="loadingFlag"
                    :data="tableData"
                    :height="tableHeight"
                    ref="table"
                    border
                    stripe
                    style="width: 100%"
                >
                    <el-table-column
                        prop="serialNumber"
                        label="序号"
                        width="60"
                        :show-overflow-tooltip="true"
                        fixed
                        >
                    </el-table-column>
                    <el-table-column
                        prop="phone"
                        label="手机号"
                        width="120"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="userName"
                        label="姓名"
                        width="120"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="nickName"
                        label="用户名"
                        width="120"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        label="性别"
                        width="80"
                        :show-overflow-tooltip="true"
                        >
                        <template slot-scope="scope">
                            <span>{{scope.row.gender == 1 ? '男' : scope.row.gender == 2 ? '女' : '未知'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="dept"
                        label="部门"
                        width="160"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="roleName"
                        label="角色"
                        width="160"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="createUser"
                        label="创建人"
                        width="160"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="创建时间"
                        width="160"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        label="状态"
                        width="100"
                        :show-overflow-tooltip="true"
                        >
                        <template slot-scope="scope">
                            <span>{{scope.row.valid == 1 ? '正常' : '禁用'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        fixed="right">
                        <template slot-scope="scope">
                            <el-button @click="editInfoFn(scope.row.id)" type="text" size="small" v-if="editBtn">编辑</el-button>
                            <el-button @click="deleteInfoFn(scope.row.id)" type="text" size="small" v-if="deleteBtn">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 页码 -->
            <div class="content-Page-container">
                <BaseFormPage 
                    :pagination="pagination"
                    @cFirstPageFn="cFirstPageFn"
                    @cLastPageFn="cLastPageFn"
                    @cJumpPageFn="cJumpPageFn"
                    @cPreFn="cPreFn"
                    @cNextFn="cNextFn"
                    @cRefreshFn="cRefreshFn"
                    >
                </BaseFormPage>
            </div>
        </div>

        <!-- 新增/编辑 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFlag"
            width="448px"
            :show-close="false"
            center
            class="account-dialog-content">
            <div class="dialog-wrap">
                <el-form 
                    :model="ruleForm" 
                    :rules="rules" 
                    ref="ruleForm" 
                    :hide-required-asterisk="true"
                    label-width="80px" 
                    class="form-box"
                >
                    <el-form-item label="姓名：" prop="userName">
                        <el-input 
                            v-model="ruleForm.userName" 
                            placeholder="请输入姓名" 
                            maxlength="20"
                            clearable>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="手机号：" prop="phone">
                        <el-input 
                            v-model.number="ruleForm.phone" 
                            placeholder="请输入手机号" 
                            maxlength="11"
                            show-word-limit
                            clearable>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="用户名：" prop="nickName">
                        <el-input 
                            v-model="ruleForm.nickName" 
                            placeholder="请输入用户名" 
                            maxlength="20"
                            clearable>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="性别：" prop="gender">
                        <el-select v-model="ruleForm.gender" placeholder="请选择">
                            <el-option label="未知" value="-1"></el-option>
                            <el-option label="男" value="1"></el-option>
                            <el-option label="女" value="2"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="部门：" prop="department">
                        <el-input 
                            v-model="ruleForm.department" 
                            placeholder="请输入部门" 
                            maxlength="20"
                            clearable>
                        </el-input>
                    </el-form-item>
                    
                    <el-form-item label="角色：" prop="roleName">
                        <el-select v-model="ruleForm.roleName" placeholder="请选择">
                            <el-option 
                                :label="item.name" 
                                :value="item.name"
                                v-for="(item, index) in roleArr"
                                :key="index"
                            ></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="状态：" prop="valid">
                        <el-select v-model="ruleForm.valid" placeholder="请选择">
                            <el-option label="正常" value="1"></el-option>
                            <el-option label="禁用" value="99"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="resetForm('ruleForm')">取 消</el-button>
                <el-button size="small" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除提示 -->
        <el-dialog
            title="删除"
            :visible.sync="delDialogFlag"
            width="340px"
            :show-close="false"
            top="30vh"
            center
            class="account-delete-wrap">
            <span>请确认是否删除此账号？</span>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="delDialogFlag = false">取 消</el-button>
                <el-button size="small" type="primary" @click="sureDeleteFn">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Storage from "@/utils/storage";
import BaseFormPage from '@/components/BaseFormPage';
export default {
    components: {
        BaseFormPage
    },
    data() {
        return {
            loadingFlag: false,         //表格数据加载状态
            dialogFlag: false,          //编辑/新增弹窗显示状态
            delDialogFlag: false,       //删除弹窗显示状态

            pageIndex: 1,
            pageSize: 20,
            tableHeight: 200,           //表格初始高度
            tableData: [],              //表格数据
            pagination: {               //分页数据
                loadingFlag: false,     //数据加载状态
                currentPage: 1,         //当前页
                totalPage: 1,           //总页数
                totalNum: 0,            //总条数
                firstNum: 0,            //分页显示起始值
                endNum: 0               //分页显示结束值
            },

            dialogTitle: '',
            isEditFlag: false,
            currentEditId: '',
            currentDelId: '',
            roleArr: [],

            ruleForm: {
                userName: '',
                phone: '',
                nickName: '',
                gender: '',
                department: '',
                roleName: '',
                valid: '',
            },
            rules: {
                userName: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { type: 'number', message: '手机号必须为数字'}
                ],
                nickName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'change' },
                ],
                department: [
                    { required: true, message: '请输入部门', trigger: 'blur' },
                ],
                roleName: [
                    { required: true, message: '请选择角色', trigger: 'change' }
                ],
                valid: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ],
            },

            addBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(288) == -1 ? false : true,
            editBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(289) == -1 ? false : true,
            deleteBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(291) == -1 ? false : true,
        }
    },
    created() {
        this.getListData()
    },
    methods: {
        getListData() {
            this.loadingFlag = true;
            this.pagination.loadingFlag = true;
            let params = {
                pgCt: this.pageIndex,
                pgSz: this.pageSize
            }

            this.$http.post('/sys_user/userAndRole', params)
                .then((res) => {
                    if(res.data.records.length > 0) {
                        this.pagination.totalPage = res.data.pages
                        this.pagination.totalNum = res.data.total
                        
                        res.data.records.forEach((item, index) => {
                            //列表下标
                            item.index = index
                            //列表序号
                            item.serialNumber = ((this.pageIndex - 1) * this.pageSize) + (index + 1)
                            item.dept = item.dept || '--'
                        })
                        this.pagination.firstNum = res.data.records[0].serialNumber
                        this.pagination.endNum = res.data.records[res.data.records.length-1].serialNumber
                    }else{
                        this.pagination.currentPage = 1
                        this.pagination.totalPage = 1
                        this.pagination.totalNum = 0
                        this.pagination.firstNum = 0
                        this.pagination.endNum = 0
                        
                        if(Storage.get('isAllotTap')) { //修复分配权限后第一次请求无数据问题
                            Storage.del('isAllotTap')
                            this.getListData()
                        }
                    }
                    this.tableData  = res.data.records;
                }).then(() => {
                    this.tableHeightFn();
                    this.loadingFlag = false;
                    this.pagination.loadingFlag = false;
                })
        },
        tableHeightFn() { //表格高度
            let tableDataLength = this.tableData.length;
            let minHeight = tableDataLength == 0 ? 0 : 80;
            this.$nextTick(function () {
                this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - minHeight;
                if(this.tableData.length <= 0) {
                    this.tableHeight = '60vh'
                }
                
                let self = this;
                window.onresize = function() {
                    self.tableHeight = window.innerHeight - self.$refs.table.$el.offsetTop - minHeight;
                    self.tableHeight = self.tableHeight < 200 ? 200 : self.tableHeight;
                }
            })
        },
        resetPageIndex() { //重置页码
            this.pagination.currentPage = 1;
            this.pageIndex = 1;
        },
        addFn() { //新增
            this.dialogTitle = '新增'
            this.dialogFlag = true
            this.isEditFlag = false
            this.getAllRoleFn()
        },
        editInfoFn(id) { //编辑
            this.dialogTitle = '编辑'
            this.dialogFlag = true
            this.isEditFlag = true
            this.currentEditId = id
            this.getAllRoleFn()
            this.getDetailFn(id)
        },
        getDetailFn(id) {
            this.$http.get('/sys_user/detail/' + id)
                .then((res) => {
                    this.ruleForm.userName = res.data.userName
                    this.ruleForm.nickName = res.data.nickName
                    this.ruleForm.phone = Number(res.data.phone)
                    this.ruleForm.gender = res.data.gender + ''
                    this.ruleForm.department = res.data.dept
                    this.ruleForm.roleName = res.data.roleName
                    this.ruleForm.valid = res.data.valid + ''
                })
        },
        getAllRoleFn() {
            let params = {
                pgCt: 1,
                pgSz: 99
            }
            this.$http.post('/role/list', params)
                .then((res) => {
                    this.roleArr = res.data.records
                })
        },

        deleteInfoFn(id) { //删除
            this.delDialogFlag = true;
            this.currentDelId = id;
        },
        sureDeleteFn() {
            this.$http.post('/sys_user/remove/' + this.currentDelId)
                .then((res) => {
                    this.delDialogFlag = false;
                    this.$message({
                        message: '已删除',
                        type: 'success'
                    });
                    setTimeout(() => {
                        this.searchFn()
                    }, 1000)
                })
        },

        submitForm(formName) { //确认提交
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let regexPhone = /^1[3456789]\d{9}$/.test(this.ruleForm.phone)
                    if(!regexPhone) {
                        this.$message.error('请输入正确的手机号')
                        return
                    }
                    this.addOrEditAccountFn()
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        addOrEditAccountFn() { //提交请求
            console.log('currentEditId:', this.currentEditId)
            let params = {
                id: this.currentEditId,
                userName: this.ruleForm.userName,
                roleName: this.ruleForm.roleName,
                nickName: this.ruleForm.nickName,
                phone: this.ruleForm.phone,
                gender: this.ruleForm.gender,
                dept: this.ruleForm.department,
                valid: this.ruleForm.valid
            }
            if(!this.isEditFlag) {
                delete params.id
            }
            console.log('params:', JSON.stringify(params))
            // return;
            this.$http.post('/sys_user/addOrUpdate', params)
                .then((res) => {
                    this.dialogFlag = false;
                    this.$message({
                        message: this.isEditFlag ? '编辑成功' : '新增成功',
                        type: 'success'
                    });
                    this.resetForm('ruleForm');
                    setTimeout(() => {
                        this.searchFn()
                    }, 1000)
                })
        },
        resetForm(formName) { //重置表单内容
            this.$refs[formName].resetFields();
            this.dialogFlag = false;
        },

        searchFn() { //搜索
            this.resetPageIndex()
            this.getListData()
        },
        cFirstPageFn(pageNum) { //首页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cLastPageFn(pageNum) { //尾页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cJumpPageFn(pageNum) { //页码跳转
            this.pageIndex = pageNum;
            this.getListData()
        },
        cPreFn(pageNum) { //上一页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cNextFn(pageNum) { //下一页
            this.pageIndex = pageNum;
            this.getListData()
        },
        resetParams() { //重置参数
            this.phone = ''
            this.userName = ''
            this.date = ''
            this.startPurchaseTime = ''
            this.endPurchaseTime = ''
            this.purchaseType = ''
            this.detailData = {}
            this.tableData = []
            this.pageIndex = 1
            this.pageSize = 20
            this.pagination = {
                loadingFlag: false,
                currentPage: 1,
                totalPage: 1,
                totalNum: 0,
                firstNum: 0,
                endNum: 0
            }
        },
        cRefreshFn() { //刷新
            this.resetParams()
            this.getListData()
        },

        changeGender() { //选择性别
            console.log('changeGender')
        },
        changeDepartment() { //选择部门
            console.log('changeDepartment')
        },
        changeRole() { //选择角色
            console.log('changeRole')
        },
        changeState() { //选择状态
            console.log('changeState')
        }
    }
}
</script>

<style lang="scss">
    .account-dialog-content {
        .dialog-wrap {
            .el-select {
                width: 100%;
            }
        }
        .el-dialog__footer {
            .el-button+.el-button {
                margin-left: 50px;
            }
        }
    }

    .account-delete-wrap {
        .el-dialog__header {
            padding: 18px 20px;
        }
        .el-dialog__body {
            padding-bottom: 24px;
            text-align: center;
        }
        .el-dialog__footer {
            .el-button+.el-button {
                margin-left: 50px;
            }
        }
    }
</style>